package com.zwj.config.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author zwj
 * @Description: 自定义拦截器
 * @date 2022/6/25 1:48 下午
 */
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("请求接口：" + request.getRequestURL());
        Map<String, String[]> map = request.getParameterMap();
        if (!map.isEmpty()) {
            String jsonStr = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
            log.info("请求参数：" + jsonStr);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 打印响应结果日志
        if (modelAndView != null && modelAndView.getModel() != null) {
            String jsonResponse = JSON.toJSONString(modelAndView.getModel(), SerializerFeature.WriteMapNullValue);
            log.info("响应结果：" + jsonResponse);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 如果有异常，记录异常信息
        if (ex != null) {
            log.error("请求处理异常：", ex);
        }
    }
}
